import { TIM, TIMUploadPlugin, Aegis } from "../pages/TUIKit/debug/tim.js";
// import RelationshipModule from "@tencentcloud/chat/modules/relationship-module.js";
// import GroupModule from "@tencentcloud/chat/modules/group-module.js";
import { genTestUserSig, aegisID } from "../pages/TUIKit/debug/index.js";
import {
  TUIConversationServer,
} from "../pages/TUIKit/TUICore/server";
import { imStore } from "@/store/imStore";
import { network } from "@/store/network";
import { userData } from "@/store/userData";
import { config as configStore } from "@/store/config";
import { loginOut as reqLoginOut,getSign} from "@/api/api";
import { getBodyData } from "@/hooks/bodyData"
import { getPublicPlanList,getArticleList } from "@/api/api";
import { noNet } from "@/utils/utils"


const setPlanStorge = () => {
	getPublicPlanList({page:1,rows:3,planType:2}).then((res:any) => {
		if(res.success){
			uni.setStorageSync('fangan',res.data.list)
		}
	});


    getArticleList({page:1,rows:3,type:1}).then((res:any)=>{
        uni.setStorageSync('zhishi',res.data.list)
    });
    getArticleList({page:1,rows:3,type:2}).then((res:any)=>{
        uni.setStorageSync('xinfa',res.data.list)
    });
}


// const config = {
//     SDKAppID: 1400818070, // Your SDKAppID
//     secretKey: "b3af4771ffbab8f86db8d5ba412e3546b23183afe3f7d5dddc8088f99b57f9ce", // Your secretKey
// };

let kickouted = false;

const login = (id: string, userSig: string,noSwitchTab:boolean) => {
  const s = configStore();
  uni.$TUIKit
    .login({ userID: id, userSig })
    .then((res) => {
		const IM_STORE = imStore();
		setTimeout(()=>{
		    IM_STORE.setReceiving(false)
			uni.hideLoading()
		},1500)
		setTimeout(()=>{
		    IM_STORE.setReceiving(false)
			uni.hideLoading()
		},1600)
		setTimeout(()=>{
		    IM_STORE.setReceiving(false)
			uni.hideLoading()
		},1700)
		getBodyData();
        if(noSwitchTab){
            return
        }
        setPlanStorge();

		/* #ifdef H5 */
		/*
		s.setPageLoaded();
		uni.switchTab({
			url: '/pages/discover/discover',
		});
		return
		*/
		/*#endif*/
		let switchTabUrl = null;
		try {
			//switchTabUrl = uni.getStorageSync('switchTabUrl');
			//uni.removeStorageSync('switchTabUrl');
		} catch (e) {
			
		}
		if(switchTabUrl){
			/*
			if(switchTabUrl == 'pages/TUIKit/TUIPages/TUIChat/index'){
				uni.navigateBack({
					delta:1,
					animationType:'none',
					success:() =>{
					}
				})
			}
			*/
			//switchTabUrl = "/pages/discover/discover";
			/*
			if(switchTabUrl == 'pages/quanzi/quanzi'){ 
				uni.switchTab({
					url: '/pages/quanzi/quanzi',
				});
			}else{
				uni.navigateTo({
					url: '/pages/TUIKit/TUIPages/TUIChat/index',
					animationType: 'none',
				});
			}
			*/
		}else{
			uni.switchTab({
				url: "/pages/discover/discover",
				success() {
					s.setPageLoaded();
					/*#ifdef APP-PLUS*/
					plus.navigator.closeSplashscreen();
					/*#endif*/
				},
			});
		}

		return;

    })
};

export const loginOut = () => {
  //offTIMEvent();
  return new Promise((resolve, reject) => {
    uni.$TUIKit.logout().then((res) => {
		//const IM_STORE = imStore();
		//IM_STORE.clearMessageList()
		resolve(true);
    });
  });
};

export const restartIm = async ()=>{
    await loginOut();
    imInit();
    const userDataStroe = userData();
    imLogin(userDataStroe.id,true);
}
export const restartImAndPage = async ()=>{
    //await loginOut();
	uni.$TUIKit.destroy().then((res) => {
		//const IM_STORE = imStore();
		//IM_STORE.clearMessageList()
		imInit();
		const userDataStroe = userData();
		console.log("重新登录IM")
		imLogin(userDataStroe.id,true);
	});
    
}
const netStateChange = (event:any)=>{
    const NETWORK = network();
    if(event.data.state!==uni.$TIM.TYPES.NET_STATE_CONNECTED){
        //noNet();
        NETWORK.setNet(false);
    }else{
        NETWORK.setNet(true);
    }
}




const bindTIMEvent = () => {
  uni.$TUIKit.on(uni.$TIM.EVENT.SDK_READY, handleSDKReady);
  uni.$TUIKit.on(uni.$TIM.EVENT.SDK_NOT_READY, handleSDKNotReady);
  uni.$TUIKit.on(uni.$TIM.EVENT.KICKED_OUT, handleKickedOut);
  uni.$TUIKit.on(uni.$TIM.EVENT.FRIEND_LIST_UPDATED, handleFriendUpdate);
  uni.$TUIKit.on(uni.$TIM.EVENT.GROUP_LIST_UPDATED, handleGroupListUpdate);
  uni.$TUIKit.on(
    uni.$TIM.EVENT.FRIEND_APPLICATION_LIST_UPDATED,
    handelFriendAddListUpdate
  );
  uni.$TUIKit.on(
    uni.$TIM.EVENT.NET_STATE_CHANGE,
    netStateChange
  );
  //uni.$TUIKit.on(uni.$TIM.EVENT.MESSAGE_RECEIVED, handleMessageAddReceived);
  uni.$TUIKit.on(uni.$TIM.EVENT.MESSAGE_REVOKED, handleMessageRevoked);
};

const offTIMEvent = () => {
  uni.$TUIKit.off(uni.$TIM.EVENT.SDK_READY, handleSDKReady);
  uni.$TUIKit.off(uni.$TIM.EVENT.SDK_NOT_READY, handleSDKNotReady);
  uni.$TUIKit.off(uni.$TIM.EVENT.KICKED_OUT, handleKickedOut);
  uni.$TUIKit.off(uni.$TIM.EVENT.FRIEND_LIST_UPDATED, handleFriendUpdate);
  uni.$TUIKit.off(uni.$TIM.EVENT.GROUP_LIST_UPDATED, handleGroupListUpdate);
  uni.$TUIKit.off(
    uni.$TIM.EVENT.FRIEND_APPLICATION_LIST_UPDATED,
    handelFriendAddListUpdate
  );
  //uni.$TUIKit.off(uni.$TIM.EVENT.MESSAGE_RECEIVED, handleMessageAddReceived);
  //uni.$TUIKit.off(uni.$TIM.EVENT.MESSAGE_REVOKED, handleMessageReceived);
};
/*
//新消息处理
const handleMessageAddReceived = (event:any) => {
	const userDataStroe = userData();
	let { data } = event;
	data.forEach((item:any) => {
		console.log(item?.payload.data)
		if(item?.payload.data == 'transfer_rob'){
			let extensionJson = JSON.parse(item.payload.extension);
			let key = extensionJson.transferId + userDataStroe.id
			uni.setStorageSync(key , extensionJson.status);
		}
	})
};
*/
const handleSDKReady = (event) => {
  uni.$emit("SDKReady");
  uni.$chat_isSDKReady = true;
  uni.hideLoading();
};

const handleSDKNotReady = (event) => {
    // uni.showToast({
    //   icon: "none",
    //   title: "SDK 未完成初始化",
    //   duration: 1500,
    // });
};

const handleKickedOut = async (event: any) => {
	uni.$emit("kickOut");
	kickouted = true;
	uni.clearStorageSync();
	uni.showToast({
		icon: "none",
		title: `您的账号已在其他设备登录`,
		duration: 5000,
	});

  await userLoginOut();
  // uni.showToast({
  //     title: `${kickedOutReason(event.data.type)}被踢出，请重新登录。`,
  //     icon: "none",
  // });
};

const handleFriendUpdate = (event) => {
  uni.$emit("friendUpdate");
};
let timerId: any = NaN;
function debounce(func: Function,event:any, wait = 200, immediate = false) {
    // 清除定时器
    if (!isNaN(timerId)) clearTimeout(timerId);
    // 立即执行，此类情况一般用不到
  
    if (immediate) {
      var callNow = !timerId;
      timerId = setTimeout(() => {
        timerId = NaN;
      }, wait);
  
      if (callNow) typeof func === "function" && func();
    } else {
      // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
      timerId = setTimeout(() => {
        typeof func === "function" && func(event);
      }, wait);
    }
  }

const updateGroupList = (event:any)=>{
    const { data } = event;
    if (!data) {
      return;
    }
    const IM_STORE = imStore();
    IM_STORE.setGroupList(data);
    uni.$emit("groupListUpdate");
}


const handleGroupListUpdate = (event: any) => {
    updateGroupList(event);
    //debounce(updateGroupList,event,);

};

const handelFriendAddListUpdate = async (event: any) => {
  console.log("FRIEND_APPLICATION_LIST_UPDATED");
  const { data } = event;
  
  if (!data) {
    return;
  }


  const applicationSentToMe = data.friendApplicationList.filter(
    (friendApplication:any) =>
      friendApplication.type === uni.$TIM.TYPES.SNS_APPLICATION_SENT_TO_ME
  );

  data.friendApplicationList = applicationSentToMe.map((item:any) => {
    return {
      ...item,
      type: "people",
    };
  });

  const IM_STORE = imStore();

  IM_STORE.setFriendshipData(data);
};

const handleMessageReceived = (event) => {
  const { data } = event;
  if (!data) {
    return;
  }


  const userDataStroe = userData();

  let needRefestAddGroupList = false;

  data.forEach((item) => {
    if (
      item.from === "@TIM#SYSTEM" &&
      item.payload.operationType === 1 &&
      item.payload.groupProfile.to === userDataStroe.id
    ) {
      needRefestAddGroupList = true;
    }
  });

  if (needRefestAddGroupList) {
    uni.$emit("updateAddGroupList");
  }
};

const kickedOutReason = (type) => {
  switch (type) {
    case uni.$TIM.TYPES.KICKED_OUT_MULT_ACCOUNT:
      return "多实例登录";
    case uni.$TIM.TYPES.KICKED_OUT_MULT_DEVICE:
      return "多设备登录";
    case uni.$TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED:
      return "userSig 过期";
    case uni.$TIM.TYPES.KICKED_OUT_REST_API:
      return "REST API kick 接口踢出";
    default:
      return "";
  }
};

export const userLoginOut = async () => {
  const res: any = await reqLoginOut();
  const { flag } = res;
  if (flag === 9000 || flag === 1) {
	//uni.clearStorage();
	const IM_STORE = imStore();
	IM_STORE.clearImData();
    const userDataStroe = userData();
    userDataStroe.clearUserData();
    const config: any = configStore();
    config.setPageUnload();
    const pages = getCurrentPages();
    if (pages.length) {
      const currenturl = pages[pages.length - 1].route;
      if (currenturl !== "pages/login/login") {
        uni.reLaunch({
          url: "/pages/login/login",
          animationType: "fade-in",
        });
      }
    } else {
      uni.redirectTo({
        url: "/pages/login/login",
      });
    }

    return true;
  }
};

const handleMessageRevoked = (event: any) => {
	const IM_STORE: any = imStore();
	IM_STORE.updateRevoke(event.data);
};

export const imInit = () => {
//   const aegis = new Aegis({
//     id: aegisID, // 项目key
//     reportApiSpeed: false, // 接口测速
//   });
  uni.platform = uni.getSystemInfoSync().platform;
//   uni.$aegis = aegis;
  // const config = {
  //     SDKAppID: 1400818070, // Your SDKAppID
  //     secretKey: "b3af4771ffbab8f86db8d5ba412e3546b23183afe3f7d5dddc8088f99b57f9ce", // Your secretKey
  // };
  const config = {
    SDKAppID: 1600022095, // Your SDKAppID
    // secretKey:
    //   "0bba722d38ad9d3ba2ae47e49c72f541b575cd5004fd957bd23c00ae12878b9e",
  };

  uni.$chat_SDKAppID = config.SDKAppID;

  uni.$TUIKit = TIM.create({
    SDKAppID: uni.$chat_SDKAppID,
    // modules: {
    //   "relationship-module": RelationshipModule,
    //   "group-module": GroupModule,
    // },
  });

  uni.$TIM = TIM;
  //uni.$TUIKit.setLogLevel(4);

  uni.$TUIKit.TUIConversationServer = new TUIConversationServer();
  //uni.$TUIKit.TUIProfileServer = new TUIProfileServer();

  //   TIM日志级别


let TUIOfflinePush = null

/*#ifdef APP-PLUS*/
TUIOfflinePush = uni.requireNativePlugin("TencentCloud-TUIOfflinePush"); //推送插件
uni.TUIOfflinePush = TUIOfflinePush;
/*#endif*/

  //   注册文件上传插件
  uni.$TUIKit.registerPlugin({
    'tim-offline-push-plugin': TUIOfflinePush,
    offlinePushConfig: {
        // huawei
        huaweiBusinessID: '', // 在腾讯云控制台上传第三方推送证书后分配的证书 ID
        // xiaomi
        xiaomiBusinessID: '',// 在腾讯云控制台上传第三方推送证书后分配的证书 ID
        xiaomiAppID: '', // 小米开放平台分配的应用 APPID
        xiaomiAppKey: '', // 小米开放平台分配的应用 APPKEY
        // meizu
        meizuBusinessID: '', // 在腾讯云控制台上传第三方推送证书后分配的证书 ID
        meizuAppID: '', // 魅族开放平台分配的应用 APPID
        meizuAppKey: '', // 魅族开放平台分配的应用 APPKEY
        // vivo
        vivoBusinessID: '', // 在腾讯云控制台上传第三方推送证书后分配的证书 ID
        // oppo
        oppoBusinessID: '', // 在腾讯云控制台上传第三方推送证书后分配的证书 ID
        oppoAppKey: '', // oppo开放平台分配的应用 AppKey
        oppoAppSecret: '', // oppo开放平台分配的应用 AppSecret
        // honor
        honorBusinessID: '',  // 在腾讯云控制台上传第三方推送证书后分配的证书 ID
        // ios
        iosBusinessID: import.meta.env.VITE_APP_PUSH_ID,   // 在腾讯云控制台上传第三方推送证书后分配的证书 ID 测试 39995  生产 40800
    }

  });
};

export const imLogin = async(id:string,noSwitchTab:boolean,) => {

//   const config1 = {
//     userID: id, //User ID
//     ...config,
//   };

//const userSig = genTestUserSig(config1).userSig;

  
    const res = await  getSign({userId:id})
    // console.log('iiiiiiiiiiiiiiiiiiiii')
    // console.log('iiiiiiiiiiiiiiiiiiiii')
    // console.log('iiiiiiiiiiiiiiiiiiiii')
    // console.log('iiiiiiiiiiiiiiiiiiiii')
    // console.log(res);

  //const userSig = genTestUserSig(config1).userSig;
  const userSig = res.data.data;
  //uni.$chat_SDKAppID = config.SDKAppID;
  uni.$chat_userID = id;
  uni.$chat_userSig = userSig;
  // 创建 sdk 实例
  //   uni.$TUIKit = TIM.create({
  //     SDKAppID: uni.$chat_SDKAppID,
  //   });
  //   uni.$TIM = TIM;
  //   uni.$TUIKit.setLogLevel(4);

  //   uni.$TUIKit.TUIConversationServer = new TUIConversationServer();
  //   uni.$TUIKit.TUIProfileServer = new TUIProfileServer();

  // //   TIM日志级别

  // //   注册文件上传插件
    uni.$TUIKit.registerPlugin({
        "tim-upload-plugin": TIMUploadPlugin,
    });
  kickouted = false;
  offTIMEvent();
  /*
  const IM_STORE = imStore();
  IM_STORE.clearMessageList()
  */
  bindTIMEvent();
  login(id, userSig,noSwitchTab);
};
